package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"news/models"
	"strconv"
	"time"
)

type NewsController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *NewsController) Add() {
	title := c.GetString("title")
	content := c.GetString("content")
	img := c.GetString("img")
	status := c.GetString("status")
	cateId, _ := c.GetInt("cateId")
	news := models.News{
		Title:    title,
		Content:  content,
		Img:      img,
		Status:   status,
		CateId:   uint(cateId),
		NewsType: models.NewsType{},
	}

	err := models.DB.Create(&news).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: news,
		}
		c.ServeJSON()
	}
}

func (c *NewsController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "请选择文件并上传",
			Data: nil,
		}
		c.ServeJSON()
	}
	defer file.Close()
	if header.Size == 2*1024*1024 {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "图片不能超过2MB",
			Data: nil,
		}
		c.ServeJSON()
	}

	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		img := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "上传成功",
			Data: img,
		}
		c.ServeJSON()
	}
}

func (c *NewsController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)

	pageData := make(map[string]interface{})
	query := models.DB.Model(&models.News{})

	key := "PAGE-" + strconv.Itoa(page) + "-" + "news"
	val, _ := models.Rdb.Get(key).Result()
	var news []models.News
	title := c.GetString("title")
	if title != "" {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: news,
		}
		c.ServeJSON()
	}

	var count int64
	query.Count(&count)
	offset := (page - 1) * size
	err := query.Preload("NewsType").Offset(offset).Limit(size).Find(&news).Error
	if err != nil {

		if err != nil {

			c.Data["json"] = JsonR{
				Code: 0,
				Msg:  "展示失败",
				Data: nil,
			}
			c.ServeJSON()
		} else {
			pageData["news"] = news
			pageData["count"] = count
			jsonByte, _ := json.Marshal(pageData)
			value := string(jsonByte)
			models.Rdb.Set(key, value, time.Second*10)
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "展示成功-mysql",
				Data: news,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), pageData)
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "展示成功-redis",
			Data: nil,
		}
		c.ServeJSON()
	}
}
